package com.hwg.emp.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hwg.emp.common.dto.KeyQueryDto;
import com.hwg.emp.common.dto.PaginationResult;
import com.hwg.emp.common.exception.EmpException;
import com.hwg.emp.common.util.ThisAppUtil;
import com.hwg.emp.model.DeptMD;
import com.hwg.emp.model.UserMD;
import com.hwg.emp.service.DeptService;
import com.hwg.emp.service.ServiceFactroy;
import com.hwg.emp.service.UserService;

public class SelectDeptsController extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			req.setCharacterEncoding("utf-8");
			resp.setCharacterEncoding("utf-8");
			String key = req.getParameter("key");
			Integer pageSize = ThisAppUtil.parseInt(req.getParameter("pageSize"), null);
			Integer pageNo = ThisAppUtil.parseInt(req.getParameter("pageNo"), null);
			DeptService serivce = ServiceFactroy.getService(DeptService.class);
			UserService userService = ServiceFactroy.getService(UserService.class);
			KeyQueryDto dto = new KeyQueryDto();
			dto.setKey(key);
			dto.setPageNo(pageNo); 
			dto.setPageSize(pageSize);
			PaginationResult<DeptMD> result = serivce.getDeptsByKey(dto);
			List<DeptMD> rows = result.getRows();
			for (int i = 0; i < rows.size(); i++) {
				UserMD user = userService.queryUserById(rows.get(i).getManager().getId());
				rows.get(i).setManager(user);
			}
			req.setAttribute("result", result);
		} catch (EmpException e) {
			req.setAttribute("message", e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("message", "系统繁忙,请稍后再试!");
		}
		req.getRequestDispatcher("/pages/showDepts.jsp").forward(req, resp);
	}
	
}
